import Vue from 'vue';
import VueRouter from 'vue-router';
import PetLogin from '../views/PetLogin.vue';
import CreateProfile from '../views/CreateProfile.vue';
import ViewProfile from '../views/ViewProfile.vue';
import PetChat from '../views/PetChat.vue';
import PetDiary from '../views/PetDiary.vue';
import PetRegister from '../views/PetRegister.vue';
import HomeView from '../views/HomeView.vue';
import PetDraw from '../views/PetDraw.vue';


import ArticleView from '@/views/ArticleView.vue';

import ArticleIndex from '@/views/ArticleIndex.vue';

import CreateArticle from '@/views/CreateArticle.vue';


Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/login',
    name: 'login',
    component: PetLogin
  },
  {
    path: '/register',
    name: 'register',
    component: PetRegister
  },
  {
    path: '/create-profile',
    name: 'create-profile',
    component: CreateProfile
  },
  {
    path: '/view-profile',
    name: 'view-profile',
    component: ViewProfile
  },
  {
    path: '/chat',
    name: 'chat',
    component: PetChat
  },
  {
    path: '/diary',
    name: 'diary',
    component: PetDiary
  },
  {
    path: '/draw',
    name: 'draw',
    component: PetDraw
  }
  ,
  {
    path: '/article',
    name: 'article',
    component: ArticleView
  }
  ,
  {
    path: '/articleIndex',
    name: 'articleIndex',
    component: ArticleIndex
  }
  ,
  {
    path: '/createArticle',
    name: 'createArticle',
    component: CreateArticle
  }
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const isLoggedIn = !!token;  // 判断用户是否登录

  if (isLoggedIn) {
    if (to.name === 'login' || to.name === 'register') {
      next({ name: 'create-profile' });
    } else {
      next();
    }
  } else {
    if (to.name === 'home' || to.name === 'login' || to.name === 'register') {
      next();
    } else {
      next({ name: 'login' });
    }
  }
});

// 防止连续点击多次路由报错
let routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(err => err)
}

export default router;
